from meiduo_admin.mypackage import *
from rest_framework.mixins import ListModelMixin, RetrieveModelMixin, UpdateModelMixin
from rest_framework.generics import GenericAPIView
from rest_framework.permissions import IsAdminUser, BasePermission

class CanChiFan(BasePermission):
    """
    Allows access only to admin users.
    """
    def has_permission(self, request, view):
        return request.user and request.user.has_perm('users.chifan')

class OrderInfoView(ListModelMixin, RetrieveModelMixin, UpdateModelMixin, GenericAPIView):
    queryset = OrderInfo.objects.all()
    serializer_class = OrderInfoModelSerializer
    pagination_class = MyPage

    # permission_classes = [CanChiFan]

    def get_queryset(self):
        # /book/(?P<pk>\d)） ---  /book/45/
        # self.kwargs = {'pk':45}

        # /book/(\d)/(\w)   -- /book/45/weiwei
        #  self.args = [45, 'weiwei']


        keyword = self.request.query_params.get('keyword')
        if keyword:
            return self.queryset.filter(order_id__contains=keyword)
        return self.queryset.all()

    def get_serializer_class(self):
        if self.kwargs.get('pk'):
            return OrderDetailModelSerializer
        return self.serializer_class

    def get(self, request, *args, **kwargs):
        order_id = kwargs.get('pk')
        if order_id:
            return self.retrieve(request, *args, **kwargs)
        return self.list(request, *args, **kwargs)

    def patch(self, request, *args, **kwargs):
        return self.partial_update(request, *args, **kwargs)
